<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
       <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <el-select style="width: 100%" v-model="params.agentId" @change="search()" filterable placeholder="--所属区域--">
              <el-option v-for="items in restaurants" :key="'restaurants'+items.id" :label="items.name" :value="items.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent ? 18 : 24" style="text-align: right">
          <el-form-item label-width="0">
            <el-button type="primary" plain icon="el-icon-plus" @click="addClass(1)">新增类别</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
   
    <pt-table
      ref="pagination"
      :params="params"
      :columns="columns"
      :dataSource="classlist"
      :options="options"
      :fetch="getTableList"
      :pagination="pagination"/>

    <el-dialog :title="editId ?'修改': '修改'+'类别'" v-dialogDrag
      :visible.sync="dialogTableVisible" width="600px" :close-on-press-escap="true">
      <el-form :model="form" ref="params" label-width="130px" size="small">
        <div class="big-class">
          <el-form-item prop="broadHeading" label="大类名称" :rules="[{ required: true, message: '请输入大类名称', trigger: 'blur' }]">
            <el-row type="flex" justify="space-between">
              <el-input style="width: 220px" v-model="form.broadHeading" placeholder="请输入大类名称" />
              <el-button type="primary" plain @click="dialogAddsubClass()">添加</el-button>
            </el-row>
          </el-form-item>
        </div>
        <div class="content" v-if="form.subType.length>0">
          <el-form-item v-for="(item,index) in form.subType" :label="'小类' + (index +1)" :key="index"
            :prop="'subType.' + index + '.name'" :rules="[{required: true, message: '小类名称不能为空', trigger: 'blur'}]">
            <el-row type="flex" justify="space-between">
              <el-input style="width: 200px" v-model="item.name" placeholder="请输入小类名称" />
              <el-button type="text" class="el-text-danger" @click.prevent="deleteSubClass(item)">删除</el-button>
            </el-row>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button class="save" :loading="isloadingSave" @click="saveCategory('params')" type="primary">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import subList from './components/subList'
  export default {
    components: { subList },
    data() {
      return {
        isloadingSave: false, //保存或修改
        dialogTableVisible: false,
        editId: '', //被编辑用户的ID
        form: { broadHeading: '', subType: [] },
        pagination: { total: 0, page: 0, size: 10, curPage: 1 }, // 分页
        options: { // 表单外观
          mutiSelect: false, //  多选则 mutiSelect
          index: false, // 显示序号
          loading: false, // 表格动画
          initTable: false // 是否一挂载就加载数据
        },
        classlist: [], //表单数据
        columns: [ // 表单配置
          { label: "大类", width: 160, align: "left", prop: 'name' },
          {
            label: "小类", minWidth: 400, align: "left",
            render: row => {
              return <sub-list item={row.subList} />;
            }
          },
          { button: true, label: "操作", width: 140, fixed: 'right',
            group: [
              { name: "查看/编辑", type: "text", style:{color: '#5155a0'}, onClick: row => this.addClass(2, row) },
              { name: "删除", type: "text", onClick: row => this.deleteClass(row.id) }
            ]
          }
        ],
        params: {
          agentId: null,
          page: 0,
          size: 10
        }
      }
    },
    computed: {
      restaurants() { // 区域据
        return this.$store.state.agentList
      }
    },
     watch: {
      restaurants: {
        handler(val) {
          if (val && val.length) {
            this.params.agentId = val[0].id
          }
        },
        deep: true,
        immediate: true
      },
      'params.agentId': {
        handler(val, old) {
          if (val) {
            if (!old) {
              this.getTableList()
            }
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      search() {
        this.pagination.curPage = 1
        this.pagination.page = 0
        this.getTableList()
      },
      addClass(type, row) { // 打开对话框，开始新增
        this.form.broadHeading = ''
        this.form.subType = []
        if (type == 1) {
          this.editId = ''
          this.dialogTableVisible = true
        } else if (type == 2) {
          this.form.broadHeading = row.name == null ? null : row.name.toString()
          row.subList.forEach((item, index) => {
            this.form.subType.push({id: item.id, name: item.name})
          })
          this.editId = row.id
          this.dialogTableVisible = true
        }
      },
      deleteClass(id) { //删除大类
        this.options.loading = true
        this.$http.post('/server/businessType/delete', JSON.stringify({ id, agent_id: this.params.agentId })) .then(res => {
          if (res.data.success) {
            this.$message({type: 'success', message: '删除成功'})
            if(this.classlist.length =='1'){
              this.pagination.curPage = 1
              this.pagination.page = 0
              this.pagination.size = 10
            }
            this.getTableList()
          }
        }).finally(() => { this.options.loading = false })
      },
      getTableList(type) { //获取分类数据
        this.options.loading = true
        const params = {...this.params }
        params.page = this.pagination.page
        params.size = this.pagination.size
        this.$http.get('/server/businessType/list?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.classlist = res.data.data.list || []
            this.pagination.total = res.data.data.total
          }
        }).finally(() => { this.options.loading = false })
      },
      deleteSubClass(item) {  //删除小类
        var index = this.form.subType.indexOf(item)
        if (index !== -1) {
          if (item.id) {
            this.$http.post('/server/businessType/delete', JSON.stringify({id: item.id, agent_id: this.params.agentId})).then(res => {
              if (res.data.success) {
                this.form.subType.splice(index, 1)
                this.getTableList()
              }
            })
          } else {
            this.form.subType.splice(index, 1)
          }
        }
      },
      dialogAddsubClass() { //添加小类
        this.form.subType.push({
          id: '', name: '',
        })
      },
      saveCategory(formName) { //保存 或修改分类
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = {...this.form, agent_id: this.params.agentId }
            this.isloadingSave = true
            if (this.editId) {
              params.id = this.editId
              this.$http.post('/server/businessType/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改成功'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingSave = false })
            } else {
              this.$http.post('/server/businessType/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '添加成功'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingSave = false })
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .sub-list {
    border-left: 1px solid #e2e2e2;
    border-right: 1px solid #e2e2e2;
    border-bottom: 1px solid #e2e2e2;
    border-radius: 0 0 4px 4px;
    max-height: 400px;
    overflow-y: auto;
    li {
      padding: 0 10px;
      border-bottom: 1px solid #e2e2e2;
      &:last-child {
        border: none;
      }
      .del {
        display: inline-block;
        text-align: center;
        margin-left: 100px;
        width: 40px;
        height: 40px;
        line-height: 45px;
      }
      i {
        font-size: 20px;
      }
    }
  }
  .big-class {
    width: 100%;
    justify-content: space-between;
    background: #eff0f5;
  }
  .content {
    max-height: 400px;
    padding: 10px 10px;
    margin-bottom: 20px;
    overflow-y: auto;
    border: 1px solid #e5e5e5;
    /*border-top: none;*/
  }
</style>
